package com.galina.notebook.test;

import java.lang.management.ManagementFactory;
import java.util.Properties;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.log4j.Logger;
import org.apache.openejb.core.LocalInitialContextFactory;
import org.junit.Before;

import junit.framework.TestCase;

public abstract class AbstractTestCase extends TestCase {
	
	private static Logger logger = Logger.getLogger(AbstractTestCase.class);
	
	public static final String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDriver";
	
	public static final String JDBC_URL = "jdbc:derby://localhost:1527/jpa_ce;create=true;";
	
	public static final String DB_USERNAME = "user";
	
	public static final String DB_PASSWORD = "test";
	
	protected InitialContext initialContext;
	
	@Before
	public void setUp() throws Exception {
		Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY,
				LocalInitialContextFactory.class.getName());

		p.put("NotebookDB", "new://Resource?type=DataSource");
		p.put("NotebookDB.JdbcDriver", JDBC_DRIVER);
		p.put("NotebookDB.JdbcUrl", JDBC_URL );
		p.put("NotebookDB.UserName", DB_USERNAME );
		p.put("NotebookDB.Password", DB_PASSWORD );
		
		p.put("NotebookDBNonJta", "new://Resource?type=DataSource");
		p.put("NotebookDBNonJta.JdbcDriver", JDBC_DRIVER);
		p.put("NotebookDBNonJta.JdbcUrl", JDBC_URL );
		p.put("NotebookDBNonJta.UserName", DB_USERNAME );
		p.put("NotebookDBNonJta.Password", DB_PASSWORD );
		p.put("NotebookDBNonJta.JtaManaged", "false" );
			
		p.put("openjpa.jdbc.SynchronizeMappings",
				"buildSchema(ForeignKeys=true)");

		initialContext = new InitialContext(p);
        
		logger.info("OpenEjb context initialized");
	}
	
    protected void setTransactionType(String transactionType) throws Exception {
        logger.info("Setting transaction-type for persistence-unit to: " + transactionType);
    	ObjectName on = new ObjectName("openejb.management:ObjectType=persistence-unit,PersistenceUnit=notebook");
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        server.invoke(on, "setTransactionType", new Object[]{transactionType}, null);
        server.invoke(on, "reload", new Object[0], null);
    };

}
